package com.copc.servlet;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Map;

@Component
public class LogFilter implements Filter {

    private static final Logger LOG = LoggerFactory.getLogger(LogFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 打印请求信息
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        LOG.info("RequestURL: {} {}", request.getRequestURL().toString(), request.getMethod());
        LOG.info("RemoteAddr: {}", request.getRemoteAddr());

        // 打印请求头信息
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            String headerValue = request.getHeader(headerName);
            LOG.info("header: {} = {}", headerName, headerValue);
        }

        // 构建一个字符串来记录方法参数
        StringBuilder paramsInfo = new StringBuilder("param: ");
        Map<String, String[]> parameterMap = request.getParameterMap();
        for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
            String paramName = entry.getKey();
            String[] paramValues = entry.getValue();
            String paramValue = String.join(",", paramValues);
            paramsInfo.append(paramName).append(" = ").append(paramValue).append(", ");
        }
        // 打印请求头信息和方法参数
        LOG.info(paramsInfo.toString());

        filterChain.doFilter(servletRequest, servletResponse);
    }
}
